<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
use think\Loader;
use PHPMailer\PHPMailer;
use think\Request;
use think\captcha\src\Captcha;

error_reporting(E_ERROR | E_PARSE );
/**
 * 是否Post请求
 * @return mixed
 */
function IsPost(){
    $IsPost = \think\Request::instance()->isPost();
    return $IsPost;
}

/**
 * 请求数据
 * @param string $str
 * @return mixed
 */
function Param($str=''){
    if($str == ''){
        $Param = \think\Request::instance()->Param();
    }else{
        $Param = \think\Request::instance()->Param($str);
    }

    return $Param;
}

//模拟get请求

function requestGet($url = '') 
{
    $postUrl = $url;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

function curlPost( $url, $data )
{
    //初使化init方法
    $ch = curl_init();

    //指定URL
    curl_setopt($ch, CURLOPT_URL, $url);

    //设定请求后返回结果
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //声明使用POST方式来进行发送
    curl_setopt($ch, CURLOPT_POST, 1);

    //发送什么数据呢
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


    //忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //忽略header头信息
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //设置超时时间
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    //发送请求
    $output = curl_exec($ch);

    //关闭curl
    curl_close($ch);

    //返回数据
    return $output;
}

function CoinClient($username, $password, $ip, $port, $timeout = 3, $headers = array(), $suppress_errors = false)
{
    return new \Common\Ext\CoinClient($username, $password, $ip, $port, $timeout, $headers, $suppress_errors);
}

/**
 * @Notes:创建助记词
 * @return string
 * @author: Qian
 * @Time: 2020/12/28 17:57
 */
function createBip39(){
    $library=Db::name('bip39')->column('word');
    $bip39All = Db::name('user_wallet_address')->column('bip39');
    do{
        $arr=array();
        for($i=0;$i<12;$i++){
            do{
                $x = $library[array_rand($library)];
            }while(in_array($x,$arr));
            array_push($arr,$x);
        }
        $str=implode(' ',$arr);
    }while(in_array($str,$bip39All));

    return $str;
}

/*2、十三位时间戳，包含毫秒1535423356248*/
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}
/**
 * @Notes:创建钱包地址
 * @param $user_id
 * @return string
 * @author: Qian
 * @Time: 2020/12/28 17:59
 */
function createAddress($user_id){
//    $address = md5(md5(msectime()).$user_id);
    $address = md5(uniqid(mt_rand(), true).$user_id);
    return "D".$address;
}

/**
 * @Notes:生成钱包私钥
 * @param $user_id
 * @param $address
 * @return string
 * @author: Qian
 * @Time: 2020/12/28 18:02
 */
function createPrivkey($address){
//    $privkey = substr(md5($address),8,16).md5(msectime());
    $privkey = substr(md5($address),8,16).md5(uniqid());
    return $privkey;
}

/**
 * @Notes:创建交易hash
 * @param $from_address
 * @param $to_address
 * @author: Qian
 * @Time: 2021/1/5 15:44
 */
function createTransHash($from_address,$to_address){
    $Hash = substr(md5(md5($from_address).uniqid()),8,16).substr(md5(md5($to_address).uniqid()),8,16).md5(uniqid());
    return $Hash;
}

function check_res($res)
{
    foreach ($res as $v) {
        if (!$v || $v == 0) {
            return false;
        }
    }

    return true;
}

function array_pos($array,$find){
    foreach ($array as $k=>$v){
        if ($v == $find){
            return $k;
        }
    }
    return false;
}
function FeedbackList(){
    $List = \think\Db::name('feedback')->order('id desc')->paginate(20);
    $FeedbackList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($FeedbackList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$FeedbackList[$k]['user_id']]);
        $FeedbackList[$k]['username'] = $UserInfo['username'];
    }

    return ['FeedbackList'=>$FeedbackList,'Page'=>$Page];
}

/**
 * 反馈记录条数
 * @return int|string
 * @throws \think\Exception
 */
function FeedbackCount(){
    $FeedbackCount = \think\Db::name('feedback')->count();
    return $FeedbackCount;
}

/**
 * 反馈详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function FeedbackInfo($Where){
    $FeedbackInfo = \think\Db::name('feedback')->where($Where)->find();
    return $FeedbackInfo;
}

/**
 * Notes:发票统计
 * User: ming
 * Date: 2022/1/23
 * Time: 23:02
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function invoiceSearchList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'create_time' => '',
        ];
    }

    if(empty($Where)){
        $List = \think\Db::name('invoice')->order('create_time desc')->order('id desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('invoice')->where($Where)->order('create_time desc')->order('id desc')->paginate('13',false,['query'=>$query]);
    }

    $UserList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $UserList as $k=>$v){
        //等级信息
        $LevelInfo = \think\Db::name('user_level')->where(['id'=>$UserList[$k]['level']])->find();
        if(empty($LevelInfo)){
            $UserList[$k]['level_name'] = "用户";
        }else{
            $UserList[$k]['level_name'] = $LevelInfo['name'];
        }

        //推荐人信息
        $RecommendInfo = UserInfo(['id'=>$UserList[$k]['recommend']]);
        $UserList[$k]['recommend'] = $RecommendInfo['username'];

//        //最大区业绩
//        $UserList[$k]['big_area_achievement'] = \think\Db::name('user')->where(['recommend'=>$v['id']])->max('recommend_achievement');
//        //小区业绩
//        $UserList[$k]['small_area_achievement'] = $v['recommend_achievement'] - $UserList[$k]['big_area_achievement'] - $v['total_spend'];
//
//        //总的余额
//        $UserList[$k]['balance_1_all'] = Db::name('user_wallet_address')->where(['user_id'=>$v['id']])->sum('balance_1');
//        $UserList[$k]['balance_2_all'] = Db::name('user_wallet_address')->where(['user_id'=>$v['id']])->sum('balance_2');
    }
    return ['UserList'=>$UserList,'Page'=>$Page];
}
/**
 * 会员列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function UserList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'level' => 999,
            'name' => '',
            'phone' => '',
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }

    if(empty($Where)){
        $List = \think\Db::name('user')->order('status desc')->order('id desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user')->where($Where)->order('status desc')->order('id desc')->paginate('13',false,['query'=>$query]);
    }

    $UserList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $UserList as $k=>$v){
        //等级信息
        $LevelInfo = \think\Db::name('user_level')->where(['id'=>$UserList[$k]['level']])->find();
        if(empty($LevelInfo)){
            $UserList[$k]['level_name'] = "用户";
        }else{
            $UserList[$k]['level_name'] = $LevelInfo['name'];
        }

        //推荐人信息
        $RecommendInfo = UserInfo(['id'=>$UserList[$k]['recommend']]);
        $UserList[$k]['recommend'] = $RecommendInfo['username'];

//        //最大区业绩
//        $UserList[$k]['big_area_achievement'] = \think\Db::name('user')->where(['recommend'=>$v['id']])->max('recommend_achievement');
//        //小区业绩
//        $UserList[$k]['small_area_achievement'] = $v['recommend_achievement'] - $UserList[$k]['big_area_achievement'] - $v['total_spend'];
//
//        //总的余额
//        $UserList[$k]['balance_1_all'] = Db::name('user_wallet_address')->where(['user_id'=>$v['id']])->sum('balance_1');
//        $UserList[$k]['balance_2_all'] = Db::name('user_wallet_address')->where(['user_id'=>$v['id']])->sum('balance_2');
    }
    return ['UserList'=>$UserList,'Page'=>$Page];
}

/**
 * 发票记录条数
 * @return int|string
 * @throws \think\Exception
 */
function InvoiceList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
           'bill'=>'',
           'limit'=>10,
            'search_type'=>'',
            'search_name'=>'',
            'begin_time' => '',
                'end_time'=>'',
         
        ];
    }

    if(empty($Where)){
        $List = \think\Db::name('invoice')->order('kp_time desc')->order('kp_time desc')->paginate($query['limit'],false,['query'=>$query]);
    }else{
        $List = \think\Db::name('invoice')->where($Where)->order('kp_time desc')->order('id desc')->paginate($query['limit'],false,['query'=>$query]);
    }

    $InvoiceList = $List->toArray()['data'];
    foreach ($InvoiceList as $k=>$v){
        $InvoiceList[$k]['tax_money'] = $v['content_tax'] + $v['content_money'];
    }
    $Page = $List->render();

    
    return ['InvoiceList'=>$InvoiceList,'Page'=>$Page];
}
/**
 * Notes:发票记录条数
 * User: ming
 * Date: 2022/1/23
 * Time: 21:06
 * @return int|string
 * @throws \think\Exception
 */
function InvoiceCount($Where=[]){
    if(empty($Where)){
        $InvoiceCount = \think\Db::name('invoice')->where(['id'=>['egt',1]])->count();
    }else{
        $InvoiceCount = \think\Db::name('invoice')->where($Where)->count();
    }

    return $InvoiceCount;
}
/**
 * 会员表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function UserCount($Where=[]){
    if(empty($Where)){
        $UserCount = \think\Db::name('user')->where(['id'=>['gt',1]])->count();
    }else{
        $UserCount = \think\Db::name('user')->where($Where)->count();
    }

    return $UserCount;
}

/**
 * 会员信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function UserInfo($Where){
    $UserInfo = \think\Db::name('user')->where($Where)->find();

    return $UserInfo;
}

//用户钱包信息
function UserWalletInfo($Where){
    $UserWalletInfo = Db::name('user_wallet_address')->where($Where)->find();
    return $UserWalletInfo;
}

function UserAddressListInfo($Where){
    $UserAddressListInfo = Db::name('user_address_list')->where($Where)->find();
    return $UserAddressListInfo;
}

//系统地址信息
function AdminAddressInfo($Where){
    $AdminAddressInfo = Db::name('admin_address')->where($Where)->find();
    return $AdminAddressInfo;
}

//生成二维码
function addQrcode($address)
{
    Vendor('phpqrcode.phpqrcode');
    //生成二维码图片
    $object = new \QRcode();

    $base = $_SERVER['DOCUMENT_ROOT'];
    $path = "/uploads/qrcode_address/";

    $ad = $base.$path . $address . '.png';
    $return = $path . $address . '.png';
//    $errorCorrectionLevel = 'H';//容错级别
//    $matrixPointSize = 7;//生成图片大小
//
//    $object->png($address, $ad, $errorCorrectionLevel, $matrixPointSize, 1);
    $level = 'H';// 纠错级别：L、M、Q、H
    $size = 7;//元素尺寸
    $margin = 1;//边距
    $outfile = 'erweima.png';
    $saveandprint = false;// true直接输出屏幕  false 保存到文件中
    $back_color = 0xFFFFFF;//白色底色
    $fore_color = 0x000000;
    $rootPath = $_SERVER['DOCUMENT_ROOT'];
//    $path = "/uploads/";
    $originalUrl = $path .$address. '.png';
    $object->png($address, $rootPath . $originalUrl, $level, $size, $margin, false, $back_color, $fore_color);
//    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_water_small.png"; //水印logo
    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_code.png"; //水印logo
    $QR = imagecreatefromstring(file_get_contents($ad));        //目标图象连接资源。
    $logo = imagecreatefromstring(file_get_contents($water));    //源图象连接资源。

    //创建一个和二维码图片一样大小的真彩色画布
    //（ps：只有这样才能保证后面copy装备图片的时候不会失真）
    $canvas = imageCreatetruecolor(imagesx($QR),imagesy($QR));

    //为真彩色画布创建白色背景，再设置为透明
    $color = imagecolorallocate($canvas, 255, 255, 255);
    imagefill($canvas, 0, 0, $color);
    //imageColorTransparent($canvas, $color); //可以设为透明背景

    //首先将二维码画布采样copy到真彩色画布中，不会失真
    imagecopyresampled($canvas,$QR,0,0,0,0,imagesx($QR),imagesy($QR), imagesx($QR),imagesy($QR));

    //再将装备图片copy到已经具有人物图像的真彩色画布中，同样也不会失真
    imagecopymerge($canvas,$logo,(imagesx($QR)-imagesx($logo))/2, (imagesy($QR)-imagesy($logo))/2,0,0,imagesx($logo),imagesy($logo), 100);

    //将画布保存到指定的png文件

    imagepng($canvas, $ad);

    imagedestroy($QR);

    imagedestroy($logo);
//    return $return;
    return $originalUrl;
}

//助记词二维码
function addQrcodeBip($bip39,$user_id)
{
    Vendor('phpqrcode.phpqrcode');
    //生成二维码图片
    $object = new \QRcode();

    $base = $_SERVER['DOCUMENT_ROOT'];
    $path = "/uploads/qrcode_address/";

    $ad = $base.$path .'bip39_'. $user_id . '.png';
    $return = $path .'bip39_'. $user_id . '.png';
    $errorCorrectionLevel = 'H';//容错级别
    $matrixPointSize = 6;//生成图片大小

    $object->png($bip39, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
//    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_water_small.png"; //水印logo
    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_code.png"; //水印logo
    $QR = imagecreatefromstring(file_get_contents($ad));        //目标图象连接资源。
    $logo = imagecreatefromstring(file_get_contents($water));    //源图象连接资源。

    //创建一个和二维码图片一样大小的真彩色画布
    //（ps：只有这样才能保证后面copy装备图片的时候不会失真）
    $canvas = imageCreatetruecolor(imagesx($QR),imagesy($QR));

    //为真彩色画布创建白色背景，再设置为透明
    $color = imagecolorallocate($canvas, 255, 255, 255);
    imagefill($canvas, 0, 0, $color);
    //imageColorTransparent($canvas, $color); //可以设为透明背景

    //首先将二维码画布采样copy到真彩色画布中，不会失真
    imagecopyresampled($canvas,$QR,0,0,0,0,imagesx($QR),imagesy($QR), imagesx($QR),imagesy($QR));

    //再将装备图片copy到已经具有人物图像的真彩色画布中，同样也不会失真
    imagecopymerge($canvas,$logo,(imagesx($QR)-imagesx($logo))/2, (imagesy($QR)-imagesy($logo))/2,0,0,imagesx($logo),imagesy($logo), 100);

    //将画布保存到指定的png文件

    imagepng($canvas, $ad);

    imagedestroy($QR);

    imagedestroy($logo);
    return $return;
}

//私钥二维码
function addQrcodePrivkey($privkey,$user_id)
{
    Vendor('phpqrcode.phpqrcode');
    //生成二维码图片
    $object = new \QRcode();

    $base = $_SERVER['DOCUMENT_ROOT'];
    $path = "/uploads/qrcode_address/";

    $ad = $base.$path .'privkey_'. $user_id . '.png';
    $return = $path .'privkey_'. $user_id . '.png';
    $errorCorrectionLevel = 'H';//容错级别
    $matrixPointSize = 6;//生成图片大小

    $object->png($privkey, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
//    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_water_small.png"; //水印logo
    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_code.png"; //水印logo
    $QR = imagecreatefromstring(file_get_contents($ad));        //目标图象连接资源。
    $logo = imagecreatefromstring(file_get_contents($water));    //源图象连接资源。

    //创建一个和二维码图片一样大小的真彩色画布
    //（ps：只有这样才能保证后面copy装备图片的时候不会失真）
    $canvas = imageCreatetruecolor(imagesx($QR),imagesy($QR));

    //为真彩色画布创建白色背景，再设置为透明
    $color = imagecolorallocate($canvas, 255, 255, 255);
    imagefill($canvas, 0, 0, $color);
    //imageColorTransparent($canvas, $color); //可以设为透明背景

    //首先将二维码画布采样copy到真彩色画布中，不会失真
    imagecopyresampled($canvas,$QR,0,0,0,0,imagesx($QR),imagesy($QR), imagesx($QR),imagesy($QR));

    //再将装备图片copy到已经具有人物图像的真彩色画布中，同样也不会失真
    imagecopymerge($canvas,$logo,(imagesx($QR)-imagesx($logo))/2, (imagesy($QR)-imagesy($logo))/2,0,0,imagesx($logo),imagesy($logo), 100);

    //将画布保存到指定的png文件

    imagepng($canvas, $ad);

    imagedestroy($QR);

    imagedestroy($logo);
    return $return;
}
function addQrcodePrivkey_bak($privkey,$user_id)
{
    Vendor('phpqrcode.phpqrcode');
    //生成二维码图片
    $object = new \QRcode();

    $base = $_SERVER['DOCUMENT_ROOT'];
    $path = "/uploads/qrcode_address/";

    $ad = $base.$path .'privkey_'. $user_id . '.png';
    $return = $path .'privkey_'. $user_id . '.png';
    $errorCorrectionLevel = 'H';//容错级别
    $matrixPointSize = 6;//生成图片大小

    $object->png($privkey, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
    $water = $_SERVER['DOCUMENT_ROOT']."/static/DBS/images/images/logo_water.png"; //水印logo
    $QR = imagecreatefromstring(file_get_contents($ad));        //目标图象连接资源。
    $logo = imagecreatefromstring(file_get_contents($water));    //源图象连接资源。

    $QR_width = imagesx($QR);            //二维码图片宽度
    $QR_height = imagesy($QR);            //二维码图片高度
    $logo_width = imagesx($logo);        //logo图片宽度
    $logo_height = imagesy($logo);        //logo图片高度
    $logo_qr_width = $QR_width / 4;       //组合之后logo的宽度(占二维码的1/5)
    $scale = $logo_width / $logo_qr_width;       //logo的宽度缩放比(本身宽度/组合后的宽度)
    $logo_qr_height = $logo_height / $scale;  //组合之后logo的高度
    $from_width = ($QR_width - $logo_qr_width) / 2;   //组合之后logo左上角所在坐标点

    //重新组合图片并调整大小
    //imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中
    imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);

    //输出图片
    imagepng($QR, $ad);
    imagedestroy($QR);
    imagedestroy($logo);
    return $return;
}

function str_padding($str){
    return str_pad($str,2,0,STR_PAD_LEFT);
}

function FindWeek($time){
    $week = \think\Config::get('week');
    $date = date('w',$time);
    return $week[$date];
}

//三王排名
function KingRank($season_id,$type,$order,$length,$where=[]){
    $season = Db::name('season')->where(['id'=>$season_id])->find();
    $appoint_ids = Db::name('appoint_reward')->where(['season_id'=>$season_id,'type'=>$type])->column('address_id'); //指定的地址数组
    $appoint_sorts = Db::name('appoint_reward')->where(['season_id'=>$season_id,'type'=>$type])->column('appoint_sort'); //指定的地址排名数组
    $whereuser['user_id'] = ['neq',1];
//    $whereuser['type'] = ['not in',[1,8]];
    $whereuser['type'] = 0;
    if (!empty($where)){
        $where = array_merge($whereuser,$where);
    }else{
        $where = $whereuser;
    }
    if (count($appoint_ids) > 0){
        //排除指定地址的所有地址的数组
        $except_address = Db::name('user_wallet_address')->where(['id'=>['not in',$appoint_ids]])->where($where)->order($order)->column('id');
        foreach ($appoint_ids as $k=>$v){
            array_splice($except_address,$appoint_sorts[$k]-1,0,$v);
        }
    }else{
        //按余额正常排名
        $except_address = Db::name('user_wallet_address')->where($where)->order($order)->column('id');
    }
    $except_address = array_slice($except_address,0,$length);
    return $except_address;
}

//邀请王排行
function InviteRank($season_id,$type,$order,$length,$where=[]){
    $season = Db::name('season')->where(['id'=>$season_id])->find();
    $appoint_ids = Db::name('appoint_reward')->where(['season_id'=>$season_id,'type'=>$type])->column('address_id'); //指定的地址数组
    $appoint_sorts = Db::name('appoint_reward')->where(['season_id'=>$season_id,'type'=>$type])->column('appoint_sort'); //指定的地址排名数组
    $whereuser['user_id'] = ['neq',1];
//    $whereuser['type'] = ['not in',[1,8]]; // 排除总地址和基金会
    $whereuser['type'] = 0; // 普通地址
//    if (!empty($where)){
//        $where = array_merge($whereuser,$where);
//    }else{
//        $where = $whereuser;
//    }
    if (count($appoint_ids) > 0){
        //排除指定地址的所有地址的数组
        $all_address = Db::name('user_wallet_address')->where(['id'=>['not in',$appoint_ids]])->where($whereuser)->select();
        foreach ($all_address as $kk=>$vv){
            //邀请的有效地址
            $effective_address = Db::name('user_wallet_address')->where(['recommend'=>$vv['id'],'balance_1'=>['egt',20],'active_time'=>['egt',$season['start_time']]])->count();
            $all_address[$kk]['recommend_effect_count'] = $effective_address;
        }
        //按照有效邀请地址数排行  相同的按照balance_1
        array_multisort(array_column($all_address,'recommend_effect_count'),SORT_DESC,array_column($all_address,'balance_1'),SORT_DESC,$all_address);
        $except_address = array_column($all_address,'id');
        foreach ($appoint_ids as $k=>$v){
            array_splice($except_address,$appoint_sorts[$k]-1,0,$v);
        }
    }else{
        //按余额正常排名
//        $except_address = Db::name('user_wallet_address')->where($where)->order($order)->column('id');
        $all_address = Db::name('user_wallet_address')->where($whereuser)->select();
        foreach ($all_address as $kk=>$vv){
            //邀请的有效地址
            $effective_address = Db::name('user_wallet_address')->where(['recommend'=>$vv['id'],'balance_1'=>['egt',20],'active_time'=>['egt',$season['start_time']]])->count();
//            if ($effective_address == 0){
//                unset($all_address[$kk]);
//                continue;
//            }
            $all_address[$kk]['recommend_effect_count'] = $effective_address;
        }
        //按照有效邀请地址数排行
        array_multisort(array_column($all_address,'recommend_effect_count'),SORT_DESC,array_column($all_address,'balance_1'),SORT_DESC,$all_address);
        $except_address = array_column($all_address,'id');
    }
    $except_address = array_slice($except_address,0,$length);
    return $except_address;
}

//获取代币余额
function getBalanceByAddress($address,$contract){
    $url = 'https://api-cn.etherscan.com/api?module=account&action=tokenbalance&contractaddress='.$contract.'&address='.$address.'&tag=latest&apikey=H4R65KDWH86I2T8CD8R4ZU5TCXBAX8M7PR';
    $resUrl = requestGet($url);
    $res = json_decode($resUrl,true);
    return $res;
}

function randFloat($min=0, $max=1,$decimal=2){
    return round($min + mt_rand()/mt_getrandmax() * ($max-$min),$decimal);
}

/**
 * 等级列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LevelList($Where=[]){
    if(empty($Where)){
        $LevelList = \think\Db::name('user_level')->select();
    }else{
        $LevelList = \think\Db::name('user_level')->where($Where)->select();
    }

    return $LevelList;
}

/**
 * 等级详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LevelInfo($Where){
    $LevelInfo = \think\Db::name('user_level')->where($Where)->find();

    return $LevelInfo;
}

/**
 * 等级申请列表
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LevelApplyList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'username' => '',
            'status' => 5,
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_level_apply')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_level_apply')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);

    }

    $LevelApplyList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $LevelApplyList as $k=>$v){
        //会员信息
        $UserInfo = \think\Db::name('user')->where(['id'=>$LevelApplyList[$k]['user_id']])->find();
        $LevelApplyList[$k]['username'] = $UserInfo['username'];

        //当前等级
        $LevelInfo = \think\Db::name('user_level')->where(['id'=>$UserInfo['level']])->find();
        if(empty($LevelInfo)){
            $LevelApplyList[$k]['now_level'] = "普通用户";
        }else{
            $LevelApplyList[$k]['now_level'] = $LevelInfo['name'];
        }

        //申请信息
        $SaveLevelInfo = \think\Db::name('user_level')->where(['id'=>$LevelApplyList[$k]['level_id']])->find();
        $LevelApplyList[$k]['level_name'] = $SaveLevelInfo['name'];

    }

    return ['LevelApplyList'=>$LevelApplyList,'Page'=>$Page];
}

/**
 * 等级申请记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function LevelApplyCount($Where=[]){
    if(empty($Where)){
        $LevelApplyCount = \think\Db::name('user_level_apply')->count();
    }else{
        $LevelApplyCount = \think\Db::name('user_level_apply')->where($Where)->count();
    }

    return $LevelApplyCount;
}

/**
 * 佣金汇总列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function FinanceSummaryList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('finance_summary')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('finance_summary')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $FinanceSummaryList = $List->toArray()['data'];
    $Page = $List->render();

    return ['FinanceSummaryList'=>$FinanceSummaryList,'Page'=>$Page];
}

/**
 * 佣金汇总记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function FinanceSummaryCount($Where=[]){
    if(empty($Where)){
        $FinanceSummaryCount = \think\Db::name('finance_summary')->count();
    }else{
        $FinanceSummaryCount = \think\Db::name('finance_summary')->where($Where)->count();
    }

    return $FinanceSummaryCount;
}

/**
 * 会员佣金汇总记录
 * @param array $Where
 * @return array
 * @throws \think\exception\DbException
 */
function FinanceUserList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
//            'username' => '',
            'summary_id' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('finance_user')->order('add_time desc')->paginate('15',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('finance_user')->where($Where)->order('add_time desc')->paginate('15',false,['query'=>$query]);
    }

    $FinanceUserList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($FinanceUserList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$FinanceUserList[$k]['user_id']]);
        $FinanceUserList[$k]['username'] = $UserInfo['username'];
        $FinanceUserList[$k]['name'] = $UserInfo['name'];
    }
    return ['FinanceUserList'=>$FinanceUserList,'Page'=>$Page];
}

/**
 * 佣金汇总记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function FinanceUserCount($Where=[]){
    if(empty($Where)){
        $FinanceUserCount = \think\Db::name('finance_user')->count();
    }else{
        $FinanceUserCount = \think\Db::name('finance_user')->where($Where)->count();
    }

    return $FinanceUserCount;
}

/**
 * 佣金列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function FinanceList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'reward_type' => 0,
            'begin_time' => '',
            'end_time' => '',
            'username' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('finance')->order('id desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('finance')->where($Where)->order('id desc')->paginate('13',false,['query'=>$query]);
    }

    $FinanceList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($FinanceList as $k=>$v){
//        if (in_array($v['reward_type'],[100])){
//            $UserInfo = UserInfo(['id'=>$v['user_id']]);
//            $FromInfo = AdminAddressInfo(['id'=>$v['from_id']]);
//        }elseif (in_array($v['reward_type'],[406])){
//            $UserInfo = AdminAddressInfo(['id'=>$v['user_id']]);
//            $FromInfo = UserWalletInfo(['id'=>$v['from_id']]);
//        }elseif (in_array($v['reward_type'],[401,403,404,405,408])){
//            $UserInfo = AdminAddressInfo(['id'=>$v['user_id']]);
//            $FromInfo = AdminAddressInfo(['id'=>$v['from_id']]);
//        }else{
//            $UserInfo = UserWalletInfo(['id'=>$v['user_id']]);
//            $FromInfo = UserWalletInfo(['id'=>$v['from_id']]);
//        }
        $UserInfo = UserInfo(['id'=>$v['user_id']]);
        $FromInfo = UserInfo(['id'=>$v['from_id']]);
//        $UserInfo = UserWalletInfo(['id'=>$v['user_id']]);
//        $FromInfo = UserWalletInfo(['id'=>$v['from_id']]);
        $FinanceList[$k]['user_name'] = $UserInfo['username'];
//        $FinanceList[$k]['usertitle'] = $UserInfo['title'];
        $FinanceList[$k]['from_name'] = $FromInfo['username'];
//        $FinanceList[$k]['fromtitle'] = $FromInfo['title'];
    }

    return ['FinanceList'=>$FinanceList,'Page'=>$Page];
}

/**
 * 佣金表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function FinanceCount($Where=[]){
    if(empty($Where)){
        $FinanceCount = \think\Db::name('finance')->count();
    }else{
        $FinanceCount = \think\Db::name('finance')->where($Where)->count();
    }

    return $FinanceCount;
}

/**
 * 佣金列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function DepositList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
//            'cycle' => 0,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_deposit')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_deposit')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $DepositList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($DepositList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$DepositList[$k]['user_id']]);
        $DepositList[$k]['user_name'] = $UserInfo['username'];

//        $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
//        $DepositList[$k]['level_name'] = $LevelInfo['name'];
    }

    return ['DepositList'=>$DepositList,'Page'=>$Page];
}

/**
 * 定存记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function DepositCount($Where=[]){
    if(empty($Where)){
        $FinanceCount = \think\Db::name('user_deposit')->count();
    }else{
        $FinanceCount = \think\Db::name('user_deposit')->where($Where)->count();
    }

    return $FinanceCount;
}

/**
 * 公告列表
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function NoticeList(){
    $List = \think\Db::name('notice')->order('add_time desc')->paginate(20);
    $NoticeList = $List->toArray()['data'];
    $Page = $List->render();
    return ['NoticeList'=>$NoticeList,'Page'=>$Page];
}


/**
 * 公告记录条数
 * @return int|string
 * @throws \think\Exception
 */
function NoticeCount(){
    $NoticeCount = \think\Db::name('notice')->count();
    return $NoticeCount;
}


/**
 * 公告详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function NoticeInfo($Where){
    $NoticeInfo = \think\Db::name('notice')->where($Where)->find();
    return $NoticeInfo;
}

/**
 * 快递列表
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function ExpressList(){
    $List = \think\Db::name('express')->paginate(20);
    $ExpressList = $List->toArray()['data'];
    $Page = $List->render();
    return ['ExpressList'=>$ExpressList,'Page'=>$Page];
}

/**
 * 快递记录条数
 * @return int|string
 * @throws \think\Exception
 */
function ExpressCount(){
    $ExpressCount = \think\Db::name('express')->count();
    return $ExpressCount;
}

/**
 * 公告评论列表
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function CommentList($NoticeID){
    $List = \think\Db::name('notice_comment')->where(['notice_id'=>$NoticeID])->order('add_time desc')->paginate(20);
    $CommentList = $List->toArray()['data'];
    foreach ($CommentList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$v['user_id']]);
        $CommentList[$k]["username"] = $UserInfo['username'];
    }
    $Page = $List->render();
    return ['CommentList'=>$CommentList,'Page'=>$Page];
}

/**
 * 公告评论记录条数
 * @return int|string
 * @throws \think\Exception
 */
function CommentCount($NoticeID){
    $CommentCount = \think\Db::name('notice_comment')->where(['notice_id'=>$NoticeID])->count();
    return $CommentCount;
}

/**
 * 商品评论列表
 * @param $NoticeID
 * @return array
 * @throws \think\exception\DbException
 */
function GoodsCommentList($GoodsID){
    $List = \think\Db::name('goods_evaluate')->where(['goods_id'=>$GoodsID])->order('add_time desc')->paginate(20);
    $CommentList = $List->toArray()['data'];
    foreach ($CommentList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$v['user_id']]);
        $CommentList[$k]["username"] = $UserInfo['username'];
        $CommentList[$k]["img"] = explode(',',$v['img_url']);
    }
    $Page = $List->render();
    return ['CommentList'=>$CommentList,'Page'=>$Page];
}

/**
 * 商品评论记录条数
 * @param $GoodsID
 * @return int|string
 * @throws \think\Exception
 */
function GoodsCommentCount($GoodsID){
    $CommentCount = \think\Db::name('goods_evaluate')->where(['goods_id'=>$GoodsID])->count();
    return $CommentCount;
}

/**
 * 添加流水明细
 * @param $user_id
 * @param $from_id
 * @param $num
 * @param $type
 * @param $reward_type
 * @param $remarks
 */
function FinanceAdd($user_id,$from_id,$num,$type,$reward_type,$remarks,$season_id='',$block_id='',$deposit_id='',$balance=0){

    $DataAdd = [
        'user_id' => $user_id,
        'from_id' => $from_id,
        'num' => $num,
        'type' => $type,
        'reward_type' => $reward_type,
        'remarks' => $remarks,
        'add_time' => time(),
        'season_id' => $season_id,
        'block_id' => $block_id,
        'deposit_id' => $deposit_id,
        'balance' => $balance,
    ];

    $Res = \think\Db::name('finance')->insert($DataAdd);
    return $Res;
}

/**
 * 银行信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function BankInfo($Where){

    $BankInfo = \think\Db::name('user_bank')->where($Where)->find();
    return $BankInfo;
}

/**
 * 提现记录
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function WithdrawList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'status' => 5,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_withdraw')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_withdraw')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $WithdrawList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($WithdrawList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$WithdrawList[$k]['user_id']]);
        $WithdrawList[$k]['user_name'] = $UserInfo['username'];
    }

    return ['WithdrawList'=>$WithdrawList,'Page'=>$Page];
}

/**
 * 提现记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function WithdrawCount($Where=[]){
    if(empty($Where)){
        $WithdrawCount = \think\Db::name('user_withdraw')->count();
    }else{
        $WithdrawCount = \think\Db::name('user_withdraw')->where($Where)->count();
    }

    return $WithdrawCount;
}

/**
 * 充值记录
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function RechargeList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'status'=>5,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_recharge')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_recharge')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $RechargeList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($RechargeList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$RechargeList[$k]['user_id']]);
        $RechargeList[$k]['user_name'] = $UserInfo['username'];
    }

    return ['RechargeList'=>$RechargeList,'Page'=>$Page];
}

/**
 * 充值记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function RechargeCount($Where=[]){
    if(empty($Where)){
        $RechargeCount = \think\Db::name('user_recharge')->count();
    }else{
        $RechargeCount = \think\Db::name('user_recharge')->where($Where)->count();
    }

    return $RechargeCount;
}

/**
 * 商品列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function GoodsList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'goods_type' => 5,
            'son_id' => 0,
            'name' => '',
            'is_shelf' => 0,
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('goods')->order('id desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('goods')->where($Where)->order('id desc')->paginate('13',false,['query'=>$query]);
    }

    $GoodsList = $List->toArray()['data'];
    $Page = $List->render();

    return ['GoodsList'=>$GoodsList,'Page'=>$Page];
}

function Goodslie($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'goods_type' => 5,
            'son_id' => 0,
            'name' => '',
            'is_shelf' => 0,
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('goods_mall')->order('id desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('goods_mall')->where($Where)->order('id desc')->paginate('13',false,['query'=>$query]);
    }

    $GoodsList = $List->toArray()['data'];
    $Page = $List->render();

    return ['GoodsList'=>$GoodsList,'Page'=>$Page];
}

/**
 * 商品表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function GoodsCount($Where=[]){
    if(empty($Where)){
        $UserCount = \think\Db::name('goods')->count();
    }else{
        $UserCount = \think\Db::name('goods')->where($Where)->count();
    }

    return $UserCount;
}

/**
 * 商品信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function GoodsInfo($Where){
    $GoodsInfo = \think\Db::name('goods')->where($Where)->find();
    return $GoodsInfo;
}

/**
 * 订单列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function OrderList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'username' => '',
            'goods_type' =>0,
            'status' => 5,
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_order')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_order')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);

    }

    $OrderList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $OrderList as $k=>$v){
        //会员信息
        $UserInfo = \think\Db::name('user')->where(['id'=>$OrderList[$k]['user_id']])->find();
        $OrderList[$k]['username'] = $UserInfo['username'];

        //产品信息
        $GoodsInfo = \think\Db::name('goods')->where(['id'=>$OrderList[$k]['goods_id']])->find();
        switch ($GoodsInfo['goods_type']) {
            case 1:
                $GoodsName = "乡村";
                break;
            case 2:
                $GoodsName = "城镇";
                break;
            case 3:
                $GoodsName = "城市";
                break;
            case 4:
                $GoodsName = "国家";
                break;
            case 5:
                $GoodsName = "帝国";
                break;
        }
        $OrderList[$k]['goods_name'] = $GoodsName;
        $OrderList[$k]['price'] = $GoodsInfo['price'];
    }

    return ['OrderList'=>$OrderList,'Page'=>$Page];
}

/**
 * 订单表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function OrderCount($Where=[]){
    if(empty($Where)){
        $OrderCount = \think\Db::name('user_order')->count();
    }else{
        $OrderCount = \think\Db::name('user_order')->where($Where)->count();
    }

    return $OrderCount;
}

/**
 * 订单信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function OrderInfo($Where){
    $OrderInfo = \think\Db::name('user_order')->where($Where)->find();

    return $OrderInfo;
}

/**
 * 意见反馈记录
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function ProposalList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'status' => 5,
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_proposal')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_proposal')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $ProposalList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($ProposalList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$ProposalList[$k]['user_id']]);
        $ProposalList[$k]['user_name'] = $UserInfo['username'];
    }

    return ['ProposalList'=>$ProposalList,'Page'=>$Page];
}

/**
 * 意见反馈记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function ProposalCount($Where=[]){
    if(empty($Where)){
        $ProposalCount = \think\Db::name('user_proposal')->count();
    }else{
        $ProposalCount = \think\Db::name('user_proposal')->where($Where)->count();
    }

    return $ProposalCount;
}

function SendEmail($Toemail,$Code){
    //系统参数
    $Config = Config();
    $toemail = $Toemail;//定义收件人的邮箱

    $mail = new PHPMailer();
    $mail->isSMTP();// 使用SMTP服务
    $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
    $mail->Host = "smtp.qq.com";// 发送方的SMTP服务器地址
    $mail->SMTPAuth = true;// 是否使用身份验证
    $mail->Username = $Config['code_email'];    //发送方邮箱
    $mail->Password = $Config['email_key'];// 发送方的邮箱授权密码
    $mail->SMTPSecure = "ssl";  //使用ssl协议方式
    $mail->Port = 465;// 邮箱的ssl协议方式端口号是465/994   QQ邮箱465 163邮箱994

    $mail->setFrom($Config['code_email'],$Config['web_name']);// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
    $mail->addAddress($toemail,$Config['web_name']);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
    $mail->addReplyTo($Config['code_email'],$Config['web_name']);// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址

    $mail->Subject = "注册验证码";// 邮件标题
    $mail->Body = "【King】尊敬的用户，您的验证码为：".$Code."，10分钟内有效，若非本人操作请忽略";// 邮件正文

    if(!$mail->send()){// 发送邮件
        return "发送失败: ".$mail->ErrorInfo;// 输出错误信息
    }else{
        return true;
    }
}

function SendEmailYahoo($Toemail,$Code){
    //系统参数
    $Config = Config();
    $toemail = $Toemail;//定义收件人的邮箱

    $mail = new PHPMailer();
    $mail->isSMTP();// 使用SMTP服务
    $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
    $mail->Host = "smtp.mail.yahoo.com";// 发送方的SMTP服务器地址
    $mail->SMTPAuth = true;// 是否使用身份验证
//    $mail->Username = $Config['code_email'];    //发送方邮箱
//    $mail->Password = $Config['email_key'];// 发送方的邮箱授权密码
    $mail->Username = 'abcaptain95@yahoo.com';    //发送方邮箱
    $mail->Password = 'voskroozrsqatvcf';// 发送方的邮箱授权密码
    $mail->SMTPSecure = "ssl";  //使用ssl协议方式
    $mail->Port = 465;// 邮箱的ssl协议方式端口号是465/994   QQ邮箱465 163邮箱994

    $mail->setFrom($Config['code_email'],$Config['web_name']);// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
    $mail->setFrom('abcaptain95@yahoo.com','测试');// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
    $mail->addAddress($toemail,$Config['web_name']);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
    $mail->addReplyTo($Config['code_email'],$Config['web_name']);// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址

    $mail->Subject = "注册验证码";// 邮件标题
    $mail->Body = "【King】尊敬的用户，您的验证码为：".$Code."，10分钟内有效，若非本人操作请忽略";// 邮件正文
    if(!$mail->send()){// 发送邮件
        return "发送失败: ".$mail->ErrorInfo;// 输出错误信息
    }else{
        return true;
    }
}

function SendEmailOutlook($Toemail,$Code){
    //系统参数
    $Config = Config();
    $toemail = $Toemail;//定义收件人的邮箱

    $mail = new PHPMailer();
    $mail->isSMTP();// 使用SMTP服务
    $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
    $mail->Host = "smtp.office365.com";// 发送方的SMTP服务器地址
    $mail->SMTPAuth = true;// 是否使用身份验证
    $mail->Username = $Config['code_email'];    //发送方邮箱
    $mail->Password = $Config['email_key'];// 发送方的邮箱授权密码
    $mail->SMTPSecure = "STARTTLS";  //使用ssl协议方式
    $mail->Port = 587;// 邮箱的ssl协议方式端口号是465/994   QQ邮箱465 163邮箱994

    $mail->setFrom($Config['code_email'],$Config['web_name']);// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
    $mail->addAddress($toemail,$Config['web_name']);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
    $mail->addReplyTo($Config['code_email'],$Config['web_name']);// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址

    $mail->Subject = "注册验证码";// 邮件标题
    $mail->Body = "【".$Config['web_name']."】尊敬的用户，您的验证码为：".$Code."，10分钟内有效，若非本人操作请忽略";// 邮件正文
    if(!$mail->send()){// 发送邮件
        return "发送失败: ".$mail->ErrorInfo;// 输出错误信息
    }else{
        return true;
    }
}
/**
 * 系统参数
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function Config(){

    $Config = \think\Db::name('system_config')->where(['id'=>1])->find();

    return $Config;
}

/**
 * 保存手机/邮箱验证码信息
 * @param $phone
 * @param $code
 */
function AddCode($phone_email,$code,$type){
    $Data = [
        'phone_email' => $phone_email,
        'code' => $code,
        'send_time' => time(),
        'type' => $type,
    ];
    \think\Db::name('user_code')->insert($Data);
}

/**
 * 判断验证码是否正确
 * @param $phone
 * @param $code
 * @return array
 */
function checkCode($phone_email,$code,$type)
{
    //根据手机号找出最后一条验证码
    $CodeInfo = \think\Db::name('user_code')->where(['phone_email' => $phone_email,'type'=>$type])->order('send_time desc')->find();
    //判断验证码是否存在
    if(empty($CodeInfo)){
        return ['status'=>0,'message'=>'验证码不存在'];
    }
    //输入的验证码是否一致
    if($CodeInfo['code'] != $code){
        return ['status'=>0,'message'=>'验证码错误'];
    }
    //判断验证码已发送多长时间
    $Duration = (time() - $CodeInfo['send_time']) / 60 ;
    if($Duration > 10){  //有效期10分钟
        return ['status'=>0,'message'=>'验证码已过期'];
    }
    //判断验证码状态
    if($CodeInfo['status'] == 1){
        return ['status'=>0,'message'=>'验证码已失效'];
    }

    //验证通过
    //通过后改变验证码使用状态
    \think\Db::name('user_code')->where(['id'=>$CodeInfo['id']])->update(['status'=>1]);
    //返回信息
    return ['status'=>1];
}




/**
 * 获取随机数
 * @param int $len
 * @return bool|string
 */
function randNumber($len = 6)
{
    $chars = str_repeat('0123456789', 10);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

//随机字符串
function randString($len = 6)
{
//    $chars = str_repeat('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 10);
    $chars = str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 10);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

function Verify(){
    $config =    [
        // 验证码字体大小
        'fontSize'    =>    15,
        // 验证码位数
        'length'      =>    4,
        // 关闭验证码杂点
        'useNoise'    =>    false,
        'useCurve'    =>    false,
//        'codeSet'    =>    '2345678190',

    ];
    $captcha = new Captcha($config);
    return $captcha->entry();
}

function CheckVerify($code,$id=''){
    $captcha = new Captcha();
    return $captcha->check($code, $id);
}

/**
 * 检查是否是微信浏览器访问
 */
function IsWechatBrowser(){
    if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false) {
        return false;
    }else{
        return true;
    }
}

/**
 * 用于请求微信接口获取数据
 * @param $url
 * @param bool $post
 * @return bool|string
 */
function get_by_curl($url,$post = false){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if($post){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

/**
 * 支付宝支付
 * @param $post
 * @param $notify_url
 * @param $return_url
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function alipay($post,$notify_url,$return_url){
    $config = Config();
    $arr=[
        'app_id'=>$config['ali_appid'], //支付AppID
        'merchant_private_key'=>$config['ali_merchant_private_key'],    //商户私钥
        'notify_url'=>$notify_url,  //回调地址（异步）
        'return_url'=>$return_url,  //回调地址（同步）
        'charset'=>$config['ali_charset'],  //编码格式
        'sign_type'=>$config['ali_sign_type'],  //签名方式
        'gatewayUrl'=>$config['ali_gateway_url'],   //支付网关
        'alipay_public_key'=>$config['ali_alipay_public_key']   //支付宝公钥
    ];

    vendor('alipay.wappay.service.AlipayTradeService');
    vendor('alipay.wappay.buildermodel.AlipayTradeWapPayContentBuilder');

    $out_trade_no = trim($post['WIDout_trade_no']);
    $subject = trim($post['WIDsubject']);
    $total_amount = trim($post['WIDtotal_amount']);
    $body = trim($post['WIDbody']);
    $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
    $payRequestBuilder->setBody($body);
    $payRequestBuilder->setSubject($subject);
    $payRequestBuilder->setTotalAmount($total_amount);
    $payRequestBuilder->setOutTradeNo($out_trade_no);
    $aop = new \AlipayTradeService($arr);
    $response = $aop->wapPay($payRequestBuilder, $arr['return_url'], $arr['notify_url']);
}

/**
 * 敏感词过滤
 * @param $text
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LexicalFiltering($text){
    $SwordList = \think\Db::name('sword')->select();

    foreach ($SwordList as $k=>$v){
        if(strpos($text,$v['sword']) !== false){
            return $v['sword'];
        }
    }
}

function AdminLog($admin_id,$username='admin',$tips='登录'){
    $ip = Request::instance()->ip();
    $add['admin_id'] = $admin_id;
    $add['name'] = $username;
    $add['tips'] = $tips;
    $add['time'] = time();
    $add['ip'] = $ip;
    Db::name('admin_log')->insert($add);
}

function UserLog($user_id,$username='',$tips=''){
    $ip = Request::instance()->ip();
    $add['user_id'] = $user_id;
    $add['name'] = $username;
    $add['tips'] = $tips;
    $add['time'] = time();
    $add['ip'] = $ip;
    Db::name('user_log')->insert($add);
}

function ReturnMsg($status,$message,$data=[],$url=''){
    return ['status'=>$status,'message'=>$message,'data'=>$data,'url'=>$url];
}
//创建TRX地址
function CreateTrxAddress(){
    try {
        $tron = new \IEXBase\TronAPI\Tron();
        $data = array();
        $generateAddress = $tron->generateAddress(); // or createAddress()
        $data = [
            'trx_address' => $generateAddress->getAddress(true),
            'trx_key' => $generateAddress->getPrivateKey(),
//            'coin' => 'TRX',
        ];
        return $data;
    } catch (\IEXBase\TronAPI\Exception\TronException $e) {
        return ($e->getMessage());
    }
}

//获取trx余额
function GetBalanceTrx($address,$coin = 'TRX'){
    vendor('autoload.php');
    $testnet = 0;
    if ($testnet == 1) {
        $node = 'https://api.shasta.trongrid.io';
    } else {
        $node = 'https://api.trongrid.io';
    }
    $fullNode = new \IEXBase\TronAPI\Provider\HttpProvider($node);
    $solidityNode = new \IEXBase\TronAPI\Provider\HttpProvider($node);
    $eventServer = new \IEXBase\TronAPI\Provider\HttpProvider($node);
    $tron = new \IEXBase\TronAPI\Tron($fullNode, $solidityNode, $eventServer);
    if ($coin == 'TRX'){
        $balance = $tron->getBalance($address, true);
    }else{
//        $tokenaddress = 'TVeT6KXPe33eGdRCzw75au5bqaSiDhtyrA'; //代币地址-正式 dbs
        $tokenaddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; //代币地址-正式 usdt
        $balance = $tron->getAccountToToken($tokenaddress, $address);
//        dump($balance);die;
    }

    return $balance;
}

//发送trx代币
/**
 * 发送交易
 * @param $coin 币种名称,如TRX,USDT等
 * @param $from 发送地址,如:TX713jumzPJ6TXPFyxFrVdH1ZypB1quZbR
 * @param $privatekey 发送地址私钥
 * @param $to 发送地址私钥
 * @param $value 发送数量
 * @param $testnet 是否为测试网络
 */
function sendTransfer($coin = 'DBS', $from, $privatekey, $to, $value, $testnet = 0) {
    if ($testnet == 1) {
        $node = 'https://api.shasta.trongrid.io';
    } else {
        $node = 'https://api.trongrid.io';
    }
    $fullNode = new \IEXBase\TronAPI\Provider\HttpProvider($node);
    $solidityNode = new \IEXBase\TronAPI\Provider\HttpProvider($node);
    $eventServer = new \IEXBase\TronAPI\Provider\HttpProvider($node);

    try {
        $tron = new \IEXBase\TronAPI\Tron($fullNode, $solidityNode, $eventServer);
        $tron->setAddress($from); //发送地址
        $tron->setPrivateKey($privatekey); //发送地址私钥

        if ($coin == 'TRX') {
//            return ['status'=>0,'message'=>'暂未开放','hash'=>'暂未开放'];
            $balance = $tron->getBalance($from, true);
            if ($balance < $value) {
//                return ('账户TRX余额不足');
                return ['status'=>0,'message'=>'账户TRX余额不足'];
            }

            $result = $tron->sendTrx($to, floatval($value));
            if ($result['result'] == true) {
                $hash = $result['txid']; //返回交易hash
                $map['time'] = time();
                $map['value'] = $value;
                $map['hash'] = $hash;
                $map['to'] = $to;
                $map['from'] = $from;
                $map['type'] = 'TRX';
                //添加写入数据库逻辑
//                return ('发送成功:' . $hash);
                return ['status'=>1,'message'=>'发送成功','hash'=>$hash];
            } else {
//                return ('失败:' . $result);
                return ['status'=>0,'message'=>'失败:' . $result,'hash'=>$result];
            }
        }
        if ($coin == 'USDT') {
            $tokenaddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; //代币地址-USDT
//            $tokenaddress = 'TVeT6KXPe33eGdRCzw75au5bqaSiDhtyrA'; //代币地址-DBS
//            $tokenaddress = 'TJeD7ta47WUaXFcVNdP9Vkp9wgqGwtVLkC'; //代币地址-测试
            // $tokenaddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; //代币地址-正式
            $balance = $tron->getAccountToToken($tokenaddress, $from);
//            dump($balance);die;

            if ($balance < $value) {
//                return ('账户' . $coin . '余额不足');
                return ['status'=>0,'message'=>'账户' . $coin . '余额不足'];
            }
            $result = $tron->transferToToken($tokenaddress, $to, $value, $from);
            if ($result['result'] == true) {
                $hash = $result['txid']; //返回交易hash
//                $map['time'] = time();
//                $map['value'] = $value;
//                $map['hash'] = $hash;
//                $map['to'] = $to;
//                $map['from'] = $from;
//                $map['type'] = 'TRC20_USDT';
                //添加写入数据库逻辑
//                return ('发送成功:' . $hash);
                return ['status'=>1,'message'=>'发送成功','hash'=>$hash];
            } else {
//                return ('失败:' . $result);
                return ['status'=>0,'message'=>'失败:' . $result,'hash'=>$result];
            }
        }
    } catch (\IEXBase\TronAPI\Exception\TronException $e) {
//        return ($e->getMessage());
        return ['status'=>0,'message'=>$e->getMessage()];
    }
}

function accountHistory($user_id,$account, $contractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'){

    if(empty($account) || empty($contractAddress)){
        return '参数不全';
    }
//    $lastcheck = file_get_contents('USDT_last_check'); //获取上次检测时间戳
//    if (!$lastcheck) {
//        $sincetime = 0;//从最账户最早的时间开始查询
//        $lastcheck = file_put_contents('USDT_last_check', $sincetime); //如果文件不存在创建文件，并写入内容
//    } else {
//        $sincetime = $lastcheck;
//    }
    $sincetime = 0;
//    file_put_contents('USDT_last_check',  time() * 1000);
    $url='https://api.trongrid.io/v1/accounts/'.$account.'/transactions/trc20?only_confirmed=true&only_to=true&min_timestamp='.$sincetime.'&limit=200&contract_address='.$contractAddress;
    $callback=file_get_contents($url);
    $thedata=json_decode($callback,true);
    if($thedata['success']==true && is_array($thedata['data'])){
        $result = handleAccount($user_id,$thedata,$url);
    }else{
        $result ='无记录';
    }
    //写入数据库$result
    return $result;
}

function handleAccount($user_id,$calldata,$url,$next='',$data=[]){
    if($next){
        $newcall=file_get_contents($url);
        $calldata=json_decode($newcall,true);
    }
    try {
        $tron = new \IEXBase\TronAPI\Tron();
//        $season = Db::name('season')->where(['status'=>1])->find();
//        $max_block = Db::name('block')->max('block');
        foreach ($calldata['data'] as $v){
            $from = $v['from']; //发送地址
            $to = $v['to']; //接受地址
            $hash = $v['transaction_id']; //区块hash
//            $amount = $tron->fromTron($v['value']); //数量
            $amount = $v['value']/pow(10,6); //数量
            $isempty = Db::name('user_recharge')->where(['hash'=> $v['transaction_id']])->find();
            if (!$isempty){
                //hash没有存储过
                if ($amount > 0) {
                    //数量 大于1才进行记录
                    $data[] = [
                        'user_id' => $user_id, //地址账户
                        'type' => 1, //币种
                        'address' => $to, //接受者
                        'from_address' => $from, //发送者
                        'add_time' => $v['block_timestamp']/1000, //区块时间戳(毫秒级)
                        'hash' => $hash, //交易hash
                        'num' => $amount, //数量
                        'status' => 1, //
                        'sure_time' => time(), //
//                        'type' => $v['token_info']['symbol'], //币种
                    ];
                    $info = [
                        'user_id' => $user_id, //地址账户
                        'type' => 1, //币种
                        'address' => $to, //接受者
                        'from_address' => $from, //发送者
                        'add_time' => $v['block_timestamp']/1000, //区块时间戳(毫秒级)
                        'hash' => $hash, //交易hash
                        'num' => $amount, //数量
                        'status' => 1, //
                        'sure_time' => time(), //
//                        'type' => $v['token_info']['symbol'], //币种
                    ];

                    //充值记录入库
                    $recharge_id = Db::name('user_recharge')->insertGetId($info);  //关联充值id
                    Db::name('user')->where(['id'=>$user_id])->setInc('balance_1',$amount);
                    FinanceAdd($user_id,$user_id,$amount,1,3,'充币USDT(TRC20)','','',$recharge_id,UserInfo(['id'=>$user_id])['balance_1']);
                }
            }

        }
        if($calldata['meta']['fingerprint']){ //处理分页数据
            $newurl=$calldata['meta']['links']['next'];
            $data=handleAccount($user_id,'',$newurl,$calldata['meta']['fingerprint'],$data);
        }
        return ($data);
    } catch (\IEXBase\TronAPI\Exception\TronException $e) {
        return ($e->getMessage());
    }
}

function NewSeason($start_block,$settle_block){
    $max_number = Db::name('season')->where(['status'=>2])->max('season_number');
    $new['season_number'] = $max_number + 1;
    $new['status'] = 1;
    $new['start_block'] = $start_block;
    $new['end_block'] = $start_block + $settle_block*10;
    $new['start_time'] = time();
    $new['end_time'] = time() + 5*$settle_block*10*60*60;
    return Db::name('season')->insert($new);
}

/********************************************台湾*********************************************/

/**
 * Notes:
 * Time: 2021/12/27  17:41
 * User: Qian
 * @param $search_array
 * @param $search_value
 * @param $search_key_name
 */
function search_array_key($search_array,$search_value,$search_key_name){
    $found_key = array_search($search_value,array_column($search_array,$search_key_name));
    return $found_key;
}

/**
 * Notes:查询数组量很大时用一个变量 避免搜索每个元素时都调用array_column
 * Time: 2021/12/27  17:52
 * User: Qian
 * @param $search_array
 * @param $search_value
 * @param $search_key_name
 * @return false|int|string
 */
function search_array_key1($search_array,$search_value,$search_key_name){
    $search_key_name_arr = array_column($search_array,$search_key_name);
    $found_key = array_search($search_value,$search_key_name_arr);
    return $found_key;
}

/**
 * Notes:检查网图是否完成
 * Time: 2021/12/27  11:38
 * User: Qian
 * @param $map_id
 */
function CheckMap($map_id){
    $map = Db::name('user_map')->where(['id'=>$map_id,'status'=>1])->find();
    if ($map){
        //网图存在
        //虚拟他用户
        $virtual = Db::name('user')->where(['role'=>2])->select();
        $map_bottom = Db::name('user_map')->where(['map_number'=>$map['map_number'],'map_level'=>5])->count();
        $max_cycle = Db::name('user_map')->max('cycle',false);
        if ($map_bottom >= 9){
            //第5层满9个用户
            //更新状态
            Db::name('user_map')->where(['map_number'=>$map['map_number']])->update(['status'=>2]);//已完成
            $current_map = Db::name('user_map')->where(['map_number'=>$map['map_number']])->select();
            $index_p1 = search_array_key($current_map,'1','position');
            $index_p2 = search_array_key($current_map,'2','position');
            $index_p3 = search_array_key($current_map,'3','position');
            $index_p4 = search_array_key($current_map,'4','position');
            $index_p5 = search_array_key($current_map,'5','position');
            $index_p6 = search_array_key($current_map,'6','position');
            $index_p7 = search_array_key($current_map,'7','position');
            $index_p8 = search_array_key($current_map,'8','position');
            $index_p9 = search_array_key($current_map,'9','position');
            $index_p10 = search_array_key($current_map,'10','position');
            $index_p11 = search_array_key($current_map,'11','position');
            $index_p12 = search_array_key($current_map,'12','position');
            $index_p13 = search_array_key($current_map,'13','position');
            $index_p14 = search_array_key($current_map,'14','position');
            $index_p15 = search_array_key($current_map,'15','position');
            $index_p16 = search_array_key($current_map,'16','position');
            $index_p17 = search_array_key($current_map,'17','position');
            //清除未完成的奖金 (第二层)
            $check_user_layer2 = $current_map[$index_p2];
//            Db::name('user_reward')->where(['user_id'=>$check_user_layer2,'is_settle'=>0])->update(['is_settle'=>2,'remarks'=>'--未完成推荐清除：'.date('m-d H:i')]);
            //检查是否有未结算的

            Db::name('user_reward')->where(['user_id'=>$check_user_layer2['user_id'],'is_settle'=>0,'map_id'=>$check_user_layer2['id']])
                ->update(['is_settle'=>2,'remarks'=>'--未完成推荐清除：'.date('m-d H:i')]);
            //分裂3个盘
            //第一个盘
            for ($i=1;$i<=8;$i++){
                $add1[$i]['break_from'] = '';
                $add1[$i]['user_role'] = 1;
                if ($i == 1){
                    $add1[$i]['user_id'] = $current_map[$index_p2]['user_id'];
                    $add1[$i]['break_from'] = $map['map_number']; //从哪个网图分裂
                }elseif ($i == 2){
                    $add1[$i]['user_id'] = $current_map[$index_p3]['user_id'];
                }elseif ($i == 3){
                    $add1[$i]['user_id'] = $current_map[$index_p6]['user_id'];
                }elseif ($i == 4){
                    //上级
                    $each_user = UserInfo(['id'=>$current_map[$index_p6]['user_id']]);
                    $each_recommend = UserInfo(['id'=>$each_user['recommend']]);
                    if (!$each_recommend || $each_recommend['id'] == 1){
                        $a1 = array_rand($virtual,1);
                        $add1[$i]['user_id'] = $virtual[$a1]['id'];
                        $add1[$i]['user_role'] = 2;
                    }else{
                        $add1[$i]['user_id'] = $each_recommend['id'];
                    }
                }elseif ($i == 5){
                    //随机虚拟
                    $a1 = array_rand($virtual,1);
                    $add1[$i]['user_id'] = $virtual[$a1]['id'];
                    $add1[$i]['user_role'] = 2;
                }elseif ($i == 6){
                    // 1 4 7  对应 index 9 12 15
                    $add1[$i]['user_id'] = $current_map[$index_p9]['user_id'];
                }elseif ($i == 7){
                    //
                    $add1[$i]['user_id'] = $current_map[$index_p12]['user_id'];
                }else{
                    //i=8
                    $add1[$i]['user_id'] = $current_map[$index_p15]['user_id'];
                }
                $add1[$i]['cycle'] = $max_cycle + 1;
                $add1[$i]['match_type'] = $map['match_type'];
                $add1[$i]['map_number'] = 'MAP'.str_pad($max_cycle+1,8,0,STR_PAD_LEFT);
                $add1[$i]['map_level'] = \think\Config::get('map_top')[$i]['map_level'];
                $add1[$i]['position'] = \think\Config::get('map_top')[$i]['position'];
                $add1[$i]['add_time'] = time();
            }
            Db::name('user_map')->insertAll($add1);
            //第二个盘
            for ($i=1;$i<=8;$i++){
                $add2[$i]['break_from'] = '';
                $add2[$i]['user_role'] = 1;
                if ($i == 1){
                    $add2[$i]['user_id'] = $current_map[$index_p2]['user_id'];
                    $add2[$i]['break_from'] = $map['map_number']; //从哪个网图分裂
                }elseif ($i == 2){
                    $add2[$i]['user_id'] = $current_map[$index_p4]['user_id'];
                }elseif ($i == 3){
                    $add2[$i]['user_id'] = $current_map[$index_p7]['user_id'];
                }elseif ($i == 4){
                    //上级
                    $each_user = UserInfo(['id'=>$current_map[$index_p7]['user_id']]);
                    $each_recommend = UserInfo(['id'=>$each_user['recommend']]);
                    if (!$each_recommend || $each_recommend['id'] == 1){
                        $a2 = array_rand($virtual,1);
                        $add2[$i]['user_id'] = $virtual[$a2]['id'];
                        $add2[$i]['user_role'] = 2;
                    }else{
                        $add2[$i]['user_id'] = $each_recommend['id'];
                    }
                }elseif ($i == 5){
                    //随机虚拟
                    $a2 = array_rand($virtual,1);
                    $add2[$i]['user_id'] = $virtual[$a2]['id'];
                    $add2[$i]['user_role'] = 2;
                }elseif ($i == 6){
                    // 1 4 7  对应 index 10 13 16
                    $add2[$i]['user_id'] = $current_map[$index_p10]['user_id'];
                }elseif ($i == 7){
                    //
                    $add2[$i]['user_id'] = $current_map[$index_p13]['user_id'];
                }else{
                    //i=8
                    $add2[$i]['user_id'] = $current_map[$index_p16]['user_id'];
                }
                $add2[$i]['cycle'] = $max_cycle + 2;
                $add2[$i]['match_type'] = $map['match_type'];
                $add2[$i]['map_number'] = 'MAP'.str_pad($max_cycle+2,8,0,STR_PAD_LEFT);
                $add2[$i]['map_level'] = \think\Config::get('map_top')[$i]['map_level'];
                $add2[$i]['position'] = \think\Config::get('map_top')[$i]['position'];
                $add2[$i]['add_time'] = time();
            }
            Db::name('user_map')->insertAll($add2);

            //第三个盘
            for ($i=1;$i<=8;$i++){
                $add3[$i]['break_from'] = '';
                $add3[$i]['user_role'] = 1;
                if ($i == 1){
                    $add3[$i]['user_id'] = $current_map[$index_p2]['user_id'];
                    $add3[$i]['break_from'] = $map['map_number']; //从哪个网图分裂
                }elseif ($i == 2){
                    $add3[$i]['user_id'] = $current_map[$index_p5]['user_id'];
                }elseif ($i == 3){
                    $add3[$i]['user_id'] = $current_map[$index_p8]['user_id'];
                }elseif ($i == 4){
                    //上级
                    $each_user = UserInfo(['id'=>$current_map[$index_p8]['user_id']]);
                    $each_recommend = UserInfo(['id'=>$each_user['recommend']]);
                    if (!$each_recommend || $each_recommend['id'] == 1){
                        $a3 = array_rand($virtual,1);
                        $add3[$i]['user_id'] = $virtual[$a3]['id'];
                        $add3[$i]['user_role'] = 2;
                    }else{
                        $add3[$i]['user_id'] = $each_recommend['id'];
                    }
                }elseif ($i == 5){
                    //随机虚拟
                    $a3 = array_rand($virtual,1);
                    $add3[$i]['user_id'] = $virtual[$a3]['id'];
                    $add3[$i]['user_role'] = 2;
                }elseif ($i == 6){
                    // 1 4 7  对应 index 11 14 17
                    $add3[$i]['user_id'] = $current_map[$index_p11]['user_id'];
                }elseif ($i == 7){
                    //
                    $add3[$i]['user_id'] = $current_map[$index_p14]['user_id'];
                }else{
                    //i=8
                    $add3[$i]['user_id'] = $current_map[$index_p17]['user_id'];
                }
                $add3[$i]['cycle'] = $max_cycle + 3;
                $add3[$i]['match_type'] = $map['match_type'];
                $add3[$i]['map_number'] = 'MAP'.str_pad($max_cycle+3,8,0,STR_PAD_LEFT);
                $add3[$i]['map_level'] = \think\Config::get('map_top')[$i]['map_level'];
                $add3[$i]['position'] = \think\Config::get('map_top')[$i]['position'];
                $add3[$i]['add_time'] = time();
            }
            Db::name('user_map')->insertAll($add3);

            //b三个网图都完成 赠送
            $check_top = $current_map[$index_p1];
            if ($check_top['break_from'] != ''){
                //是通过分裂而来的网图
                $count = Db::name('user_map')->where(['break_from'=>$check_top['break_from'],'status'=>2])->count();
                if ($count >= 3){
                    //重消的新球（分裂赠送）
                    $top_recommend = UserInfo(['id'=>$check_top['user_id']]);
                    //添加新球记录
                    $ballAdd['user_id'] = $check_top['user_id'];
                    $ballAdd['recommend_id'] = $top_recommend['recommend'];
                    $ballAdd['match_type'] = $check_top['order_type'];
                    $ballAdd['type'] = 2; //分裂赠送
                    $ballAdd['order_id'] = '';
                    $ballAdd['pay_amount'] = 0;
                    $ballAdd['add_time'] = time();
                    Db::name('user_ball')->insert($ballAdd);

//                    if ($top_recommend['recommend'] != 1){
//                        //上级网图
//                        $top_recommend_map = Db::name('user_map')->where(['user_id'=>$top_recommend['id'],'status'=>1])->select();
//                        if (count($top_recommend_map) > 0){
//                            //上级有网图
//                            $rand_index = array_rand($top_recommend_map,1);
//                            $rand_map = $top_recommend_map[$rand_index];
//                            $map_level5 = Db::name('user_map')->where(['map_level'=>5,'map_number'=>$rand_map['map_number']])->count();
//                            if ($map_level5 > 0){
//                                $max_position = Db::name('user_map')->where(['map_level'=>5,'map_number'=>$rand_map['map_number']])->max('position');
//                            }else{
//                                $max_position = 0;
//                            }
//                            //加入家族
//                            $map_add['user_id'] = $top_recommend['id'];
//                            $map_add['cycle'] = $rand_map['cycle'];
//                            $map_add['map_number'] = $rand_map['map_number'];
//                            $map_add['map_level'] = 5;
//                            $map_add['map_position'] = $max_position + 1;
//                            $map_add['add_time'] = time();
//                            $map_add['type'] = 2; //赠送
//                            $map_add['status'] = 1;
//                            $id = Db::name('user_map')->insertGetId($map_add);
//                            CheckMap($id);
//                        }
//                    }
                }
            }
        }
    }
}


/**
 * Notes:直推奖
 * @param $user_id
 * @param $recommend_id
 * @param $amount
 * Time: 2021/12/27  14:14
 * User: Qian
 */
function DirectReward($user_id,$recommend_id,$amount){
    $Config = Config();
    if ($recommend_id != 1){
        $reward = $amount * $Config['param1']/100;
        if ($reward > 0){
            Db::name('user')->where(['id'=>$recommend_id])->setInc('balance_1',$reward);
            FinanceAdd($recommend_id,$user_id,$reward,1,7,'直推奖');
        }
    }
}

/**
 * Notes:网图奖
 * Time: 2021/12/27  14:14
 * User: Qian
 * @param $user_id
 * @param $map_id
 * @param $amount
 */
function MapReward($user_id,$map_id,$amount){
    $map = Db::name('user_map')->where(['id'=>$map_id])->find();
    $Config = Config();
    if ($map){
        //第四层
        $layer4 = Db::name('user_map')->where(['map_number'=>$map['map_number'],'status'=>1,'map_level'=>4])->select();
        if ($layer4){
            $reward4 = $amount * $Config['param8']/100;
            foreach ($layer4 as $k4=>$v4){
                Db::name('user')->where(['id'=>$v4['user_id']])->setInc('balance_1',$reward4);
                FinanceAdd($v4['user_id'],$user_id,$reward4,1,8,'网图奖');
                UserRewardAdd($v4['user_id'],$user_id,$v4['id'],$v4['map_level'],$reward4,'',1);
            }
        }
        //第三层
        $layer3 = Db::name('user_map')->where(['map_number'=>$map['map_number'],'status'=>1,'map_level'=>3])->select();
        if ($layer3){
            $reward3 = $amount * $Config['param6']/100;
            foreach ($layer3 as $k3=>$v3){
                $map_recommend = UserInfo(['id'=>$v3['user_id']]);
                if ($map_recommend['recommend_count'] >= $Config['param7']){
                    //第三层直推一个
                    Db::name('user')->where(['id'=>$v3['user_id']])->setInc('balance_1',$reward3);
                    FinanceAdd($v3['user_id'],$user_id,$reward3,1,8,'网图奖');
                    UserRewardAdd($v3['user_id'],$user_id,$v3['id'],$v3['map_level'],$reward3,'',1);
                }else{
                    UserRewardAdd($v3['user_id'],$user_id,$v3['id'],$v3['map_level'],$reward3,'',0);
                }

            }
        }
        //第二层
        $layer2 = Db::name('user_map')->where(['map_number'=>$map['map_number'],'status'=>1,'map_level'=>2])->select();
        if ($layer2){
            $reward2 = $amount * $Config['param4']/100;
            foreach ($layer2 as $k2=>$v2){
                $map_recommend = UserInfo(['id'=>$v2['user_id']]);
                if ($map_recommend['recommend_count'] >= $Config['param5'] && $v2['position'] != 4){
                    //第二层直推一个
                    Db::name('user')->where(['id'=>$v2['user_id']])->setInc('balance_1',$reward2);
                    FinanceAdd($v2['user_id'],$user_id,$reward2,1,8,'网图奖');
                    UserRewardAdd($v2['user_id'],$user_id,$v2['id'],$v2['map_level'],$reward2,'',1);
                }else{
                    UserRewardAdd($v2['user_id'],$user_id,$v2['id'],$v2['map_level'],$reward2,'',0);
                }

            }
        }
        //第一层
        $layer1 = Db::name('user_map')->where(['map_number'=>$map['map_number'],'status'=>1,'map_level'=>1])->select();
        if ($layer1){
            $reward1 = $amount * $Config['param2']/100;
            foreach ($layer1 as $k1=>$v1){
                $map_recommend = UserInfo(['id'=>$v1['user_id']]);
                if ($map_recommend['recommend_count'] >= $Config['param3']){
                    //第一层直推一个
                    Db::name('user')->where(['id'=>$v1['user_id']])->setInc('balance_1',$reward1);
                    FinanceAdd($v1['user_id'],$user_id,$reward1,1,8,'网图奖');
                    UserRewardAdd($v1['user_id'],$user_id,$v1['id'],$v1['map_level'],$reward1,'',1);
                }else{
                    UserRewardAdd($v1['user_id'],$user_id,$v1['id'],$v1['map_level'],$reward1,'',0);
                }

            }
        }
    }
}

/**
 * Notes:网图奖金记录添加
 * Time: 2021/12/27  15:33
 * User: Qian
 * @param int $user_id
 * @param int $from_id
 * @param int $map_id 网图id
 * @param  int $map_level 网图第几层
 * @param float $num 奖金
 * @param string $remarks
 * @param int $is_settle 是否结算
 */
function UserRewardAdd($user_id,$from_id,$map_id,$map_level,$num,$remarks='',$is_settle=1){
    $add['user_id'] = $user_id;
    $add['from_id'] = $from_id;
    $add['map_id'] = $map_id;
    $add['map_level'] = $map_level;
    $add['num'] = $num;
    $add['add_time'] = time();
    $add['remarks'] = $remarks;
    $add['is_settle'] = $is_settle;
    if ($is_settle == 1){
        $add['settle_time'] = time();
    }
    return Db::name('user_reward')->insert($add);
}

/**
 * Notes:检查上级推荐人数
 * Time: 2021/12/28  9:44
 * User: Qian
 * @param $recommend_id
 */
function CheckRecommendCount($recommend_id){
    $Config = Config();
    $recommend_count = UserInfo(['id'=>$recommend_id])['recommend_count'];
    $check = Db::name('user_reward')->where(['user_id'=>$recommend_id,'is_settle'=>0])->count();
    if ($check > 0){
        //有待结算的奖金
        if ($recommend_count >= $Config['param3']){
            //第一层
            $unsettle_layer1 = Db::name('user_reward')->where(['user_id'=>$recommend_id,'is_settle'=>0,'map_level'=>1])->select();
            if ($unsettle_layer1){
                foreach ($unsettle_layer1 as $k=>$v){
                    Db::name('user_reward')->where(['id'=>$v['id']])->update(['is_settle'=>1,'settle_time'=>time()]);
                    Db::name('user')->where(['id'=>$recommend_id])->setInc('balance_1',$v['num']);
                    FinanceAdd($recommend_id,$v['from_id'],$v['num'],1,8,'网图奖');
                }
            }
        }
        if ($recommend_count >= $Config['param5']){
            //第二层
            $unsettle_layer2 = Db::name('user_reward')->where(['user_id'=>$recommend_id,'is_settle'=>0,'map_level'=>2])->select();
            if ($unsettle_layer2){
                foreach ($unsettle_layer2 as $k=>$v){
                    Db::name('user_reward')->where(['id'=>$v['id']])->update(['is_settle'=>1,'settle_time'=>time()]);
                    Db::name('user')->where(['id'=>$recommend_id])->setInc('balance_1',$v['num']);
                    FinanceAdd($recommend_id,$v['from_id'],$v['num'],1,8,'网图奖');
                }
            }
        }
        if ($recommend_count >= $Config['param7']){
            //第三层
            $unsettle_layer3 = Db::name('user_reward')->where(['user_id'=>$recommend_id,'is_settle'=>0,'map_level'=>3])->select();
            if ($unsettle_layer3){
                foreach ($unsettle_layer3 as $k=>$v){
                    Db::name('user_reward')->where(['id'=>$v['id']])->update(['is_settle'=>1,'settle_time'=>time()]);
                    Db::name('user')->where(['id'=>$recommend_id])->setInc('balance_1',$v['num']);
                    FinanceAdd($recommend_id,$v['from_id'],$v['num'],1,8,'网图奖');
                }
            }
        }
    }

}